package edu.dongthang.controller;

import edu.dongthang.screens.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.os.Vibrator;
import android.util.Log;
import edu.dongthang.controller.SimpleGestureFilter.SimpleGestureListener;
import android.view.View.OnTouchListener;
import android.view.*;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author thangnd
 * 
 */
public class Controller extends Activity implements OnTouchListener,
		SimpleGestureListener {

	int lastXpos = 0;
	int lastYpos = 0;
	static boolean mousemode = false;
	boolean keyboard = false;
	Thread checking;
	SimpleGestureFilter detect;
	String delim = new String("!!");
	ImageView sstmouse;
	AppDelegate appDel;
	private long startTime = 0L;	
	private Handler customHandler = new Handler();
	long timeInMilliseconds = 0L;
	long timeSwapBuff = 0L;
	long updatedTime = 0L;
	private TextView timerValue;
	// AppDelegate appDel;
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_control);

		detect = new SimpleGestureFilter(this, this);

		sstmouse = (ImageView) findViewById(R.id.stt_mouse);

		Button left = (Button) findViewById(R.id.LeftClickButton);
		Button right = (Button) findViewById(R.id.RightClickButton);
		timerValue = (TextView) findViewById(R.id.timerValue);

		Display display = getWindowManager().getDefaultDisplay();

		int width = display.getWidth();
		left.setWidth(width / 2);
		right.setWidth(width / 2);

		View touchView = (View) findViewById(R.id.TouchPad);
		touchView.setOnTouchListener(this);
		
		appDel = ((AppDelegate) getApplication());
		//dialog = ProgressDialog.show(this, "", "Đang tải ...");
	}

	public void onStart() {
		super.onStart();
		sendToAppDel(new String("Mouse Sensitivity!!"
				+ appDel.mouse_sensitivity));
		new Thread(new Runnable() {
			AppDelegate appDel = ((AppDelegate) getApplication());

			public void run() {
				while (appDel.connected) {
					try {
						Thread.sleep(1000);
					} catch (Exception e) {
					}
					;
					if (!appDel.connected) {
						finish();
					}
				}
			}
		}).start();

	}

	// detect touch events
	// and pass them to mousePadHandler method
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (mousemode == false) {
			mousePadHandler(event);
		}
		return true;
	}

	// send message to AppDelegate class
	// to be sent to server on client desktop
	private void sendToAppDel(String message) throws NullPointerException {
		//AppDelegate appDel = ((AppDelegate) getApplication());
		try {
			if (appDel.connected) {
				appDel.sendMessage(message);
			} else {
				finish();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	// ------------------------------------------------------------------------------------
	// send a mouse message
	private void mousePadHandler(MotionEvent event) {
		StringBuilder sb = new StringBuilder();

		int action = event.getAction();
		int touchCount = event.getPointerCount();

		// if a single touch
		// send movement based on action
		if (touchCount == 1) {
			switch (action) {
			case 0:
				sb.append("DOWN" + delim);
				sb.append((int) event.getX() + delim);
				sb.append((int) event.getY() + delim);
				break;

			case 1:
				sb.append("UP" + delim);
				sb.append(event.getDownTime() + delim);
				sb.append(event.getEventTime());
				break;

			case 2:
				sb.append("MOVE" + delim);
				sb.append((int) event.getX() + delim);
				sb.append((int) event.getY());
				break;

			default:
				break;
			}
		}

		// if two touches
		// send scroll message
		// based off MAC osx multi touch
		// scrolls up and down
		else if (touchCount == 2) {
			sb.append("SCROLL" + delim);
			if (action == 2) {
				sb.append("MOVE" + delim);
				sb.append((int) event.getX() + delim);
				sb.append((int) event.getY());
			} else
				sb.append("DOWN");
		}

		sendToAppDel(sb.toString());
	}

	public void LeftButtonClickHandler(View v) {
		sendToAppDel("CLICK" + delim + "LEFT");
	}

	public void RightButtonClickHandler(View v) {
		sendToAppDel("CLICK" + delim + "RIGHT");
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent me) {
		// Call onTouchEvent of SimpleGestureFilter class
		this.detect.onTouchEvent(me);
		return super.dispatchTouchEvent(me);
	}

	@Override
	public void onSwipe(int direction) {

		String str = "";

		switch (direction) {
		case SimpleGestureFilter.SWIPE_RIGHT:
			if (mousemode == true) {
				str = "Swipe Right";
				sendToAppDel("CLICK" + delim + "RIGHT");
				// vibra.vibrate(1000);
			}
			break;

		case SimpleGestureFilter.SWIPE_LEFT:
			if (mousemode == true) {
				str = "Swipe Left";
				sendToAppDel("CLICK" + delim + "LEFT");
				// vibra.vibrate(1000);
			}
			break;
		}
		//Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
		
	}

	@Override
	public void onDoubleTap() {
		sendToAppDel("MOUSE" + delim + "LEFT");
	}

	@Override
	public void onLongPress() {
		// TODO Auto-generated method stub
		if (mousemode == false) {
			mousemode = true;
			// Toast.makeText(this, "control mode", Toast.LENGTH_SHORT).show();
			sstmouse.setImageResource(R.drawable.control_icon);
			// vibra.vibrate(1000);
		} else {
			mousemode = false;
			// Toast.makeText(this, "mouse mode", Toast.LENGTH_SHORT).show();
			sstmouse.setImageResource(R.drawable.hand_icon);
			// vibra.vibrate(1000);
		}
	}

	public void clickBack(View view) {
		Intent t = new Intent(Controller.this, Touch.class);
		startActivity(t);
	}

	public void clickEsc(View view) {
		sendToAppDel("CLICK" + delim + "ESC");
		timeSwapBuff += timeInMilliseconds;
		customHandler.removeCallbacks(updateTimerThread);
	}

	public void clickF5(View view) {
		sendToAppDel("CLICK" + delim + "F5");
		startTime = SystemClock.uptimeMillis();
		customHandler.postDelayed(updateTimerThread, 0);
	}

	public void clickNote(View view) {
		//appDel.receivNote();
		//sendToAppDel("NOTE");
		
		//new NoteTask().execute(appDel);
		if(appDel.connected){
			appDel.receivNote();
			Log.d("request note", "requesting...");
		}
		Toast.makeText(Controller.this, "getting note...", Toast.LENGTH_SHORT).show();
		
	}

	public void clickMenu(View view) {

	}
	
	class NoteTask extends AsyncTask<AppDelegate, Void, Void>{
		@Override
		protected Void doInBackground(AppDelegate... params) {
			// TODO Auto-generated method stub			
			Toast t;
			t = Toast.makeText(getBaseContext(), "note da nhan duoc", Toast.LENGTH_SHORT);
			t.show();
			return null;
		}
		
	}
	
	private Runnable updateTimerThread = new Runnable() {

		public void run() {			
			timeInMilliseconds = SystemClock.uptimeMillis() - startTime;			
			updatedTime = timeSwapBuff + timeInMilliseconds;
			int secs = (int) (updatedTime / 1000);
			int mins = secs / 60;
			secs = secs % 60;
			timerValue.setText("" + mins + ":"
					+ String.format("%02d", secs));
			customHandler.postDelayed(this, 0);
			
			if(mins == 15 && secs < 2){
				Vibrator v = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
                 v.vibrate(2000);

			}
		}

	};
}
